package com.idconfirmsystem.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.dom4j.DocumentException;
import org.kymjs.kjframe.http.HttpCallBack;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.idconfirmsystem.Conf;
import com.idconfirmsystem.R;
import com.idconfirmsystem.adapter.NoticeAdapter;
import com.idconfirmsystem.dialog.SweetAlertDialog;
import com.idconfirmsystem.dialog.SweetAlertDialog.OnSweetClickListener;
import com.idconfirmsystem.lib.StringUtil;
import com.idconfirmsystem.model.Notice;
import com.idconfirmsystem.model.NoticeList;
import com.idconfirmsystem.model.NoticeQueryObj;
import com.idconfirmsystem.model.QueryRet;
import com.idconfirmsystem.remote.ConfirmApi;
import com.idconfirmsystem.util.DateUtil;
import com.idconfirmsystem.util.StringUtils;
import com.idconfirmsystem.util.XmlUtils;

public class RecevieMsgFragment extends Fragment {
	private ListView lvMsgRecevie;
	private NoticeAdapter noticeAdapter;
	List<Notice> nList;
	QueryRet<NoticeList> qRet;
	private EditText etDate;
	private DatePickerDialog datePickerDialog;
	private Button btnQuery;
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_msg_receive_list, container, false);
		initView(view);
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	private void initView(View view) {
		lvMsgRecevie = (ListView) view.findViewById(R.id.lv_msg_rec);
		
		lvMsgRecevie.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				showdialog(arg2);

			}
		});
		etDate=(EditText) view.findViewById(R.id.et_datepicker);
		etDate.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				datePickerDialog.show();
				return false;
			}
		});
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int date = calendar.get(Calendar.DATE);
		datePickerDialog = new DatePickerDialog(getActivity(), new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				// TODO Auto-generated method stub
				System.out.println(year + "-" + monthOfYear + "-" + dayOfMonth);
				StringBuilder t = new StringBuilder();
				t.append(year);
				t.append("-");
				if ((monthOfYear + 1) < 10) {
					t.append("0");
				}
				t.append(monthOfYear + 1);
				t.append("-");
				if (dayOfMonth < 10) {
					t.append("0");
				}
				t.append(dayOfMonth);
				etDate.setText(t.toString());
			}
		}, year, month, date);
		btnQuery=(Button) view.findViewById(R.id.btn_query);
		btnQuery.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				query();
			}
		});
		query();
	}

	private void showdialog(int position) {
		Notice item = nList.get(position);
		String source = item.getContent() + ".    来自：" + item.getSource_number() + "\t   ";
		if (!StringUtil.isEmpty(item.getCreate_time())) {
			source += StringUtils.friendly_time(item.getCreate_time());
		}
		source = source.replace("\\n", "\n");
		new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE).setTitleText(item.getTitle())
				.setContentText(Html.fromHtml(source).toString()).setConfirmClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						// TODO Auto-generated method stub
						sweetAlertDialog.dismiss();
					}
				}).show();
	}

	private void query() {
		String qdate=etDate.getText().toString();
		if(qdate==null||qdate.trim()==""){
			qdate=DateUtil.getCurrentDateByFormat("yyyyMMdd");
		}else {
			qdate=qdate.replace("-", "");
		}
		NoticeQueryObj queryObj = new NoticeQueryObj();
		queryObj.setDate(qdate);
		
		queryObj.setType(Conf.LoginConf.ACCOUNT_TYPE == 1 ? "SY" : "KH");
		ConfirmApi.queryData(queryObj, "NoticeService/getNoticeList", callBack);
	}

	HttpCallBack callBack = new HttpCallBack() {

		@Override
		public void onFailure(int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(errorNo, strMsg);
			System.err.println(strMsg);
		}

		@Override
		public void onSuccess(String t) {
			// TODO Auto-generated method stub
			super.onSuccess(t);
			System.out.println(t);
			try {
				qRet = XmlUtils.toBean(NoticeList.class, t);

			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			msgHandler.sendEmptyMessage(1001);
		}

	};

	private void updateList() {
		if (qRet.getTotalnum() <= 0) {
			Toast.makeText(getActivity(), "暂无消息", Toast.LENGTH_SHORT).show();
			nList=new ArrayList<Notice>();
		}else {
			nList = qRet.getResult().getNotices();
		}		
		if(noticeAdapter==null){
			noticeAdapter = new NoticeAdapter(getActivity(), lvMsgRecevie);
			lvMsgRecevie.setAdapter(noticeAdapter);
		}
		if(nList!=null){
			noticeAdapter.resetData(nList);
		}
	}

	private ReceiveMsgHandler msgHandler = new ReceiveMsgHandler();

	public class ReceiveMsgHandler extends Handler {
		public ReceiveMsgHandler() {

		}

		public ReceiveMsgHandler(Looper looper) {

		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1001:// 更新数组
				RecevieMsgFragment.this.updateList();
				break;

			default:
				break;
			}
		}

	}

}
